<template>
   <div class=''>
       
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href="/">商品管理</a></el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>

         <!-- 卡片视图区域 -->
        <el-card>
            <el-alert
                title="添加商品信息"
                type="info"
                center
                show-icon
                :close="false">
            </el-alert>
            <!-- 步骤条区域 -->
            <el-steps :space="200" :active="activeIndex - 0" finish-status="success"
                align-center
            >
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <!-- tab栏区域 -->
            <el-form :model="addForm" :rules="addFormRules"
             ref="addFormRef" label-width="100px" class="demo-ruleForm" label-position="top">
                <el-tabs :tab-position="tabPosition" v-model="activeIndex"
                    :before-leave="beforeTableave" @tab-click="tabClick"
                >
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="addForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model="addForm.goods_price"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input v-model="addForm.goods_weight"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input v-model="addForm.goods_number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="">
                            <el-cascader expand-trigger="hover"
                                v-model="addForm.goods_cat"
                                :options="cateList"
                                :props="cateProps"
                                @change="handleChange">
                            </el-cascader>
                        </el-form-item>
                        
                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="1">
                        <el-form-item :key="item.attr_id" v-for="item in manyTableData" :label="item.attr_name">
                            <!-- 复选框组 -->
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox border v-for="(items,i) in item.attr_vals" 
                                :key="i" :label="items">
                                </el-checkbox>
                            </el-checkbox-group>

                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品属性" name="2">
                         <el-form-item :label="item.attr_name"  v-for="item in onlyTableData" :key="item.id">
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                         
                    </el-tab-pane>
                    <el-tab-pane label="商品图片" name="3">
                        <!-- 上传组件没有经过拦截器，获取不到token，得手动添加 headers-->
                        <el-upload
                            class="upload-demo"
                            :action="uploadPath"
                            :on-preview="handlePreview"
                            :on-remove="handleRemove"
                            :headers="headerObj"
                            :on-success="handleSuccess"
                            list-type="picture">
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <quill-editor v-model="addForm.goods_introduce"></quill-editor>
                        <el-button type="primary" class="btnAdd" @click="add">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>
        <!-- 图片预览弹窗 -->
        <el-dialog
            title="提示"
            :visible.sync="dialogVisible"
            width="50%">
            <img :src="showPicPath" alt="" srcset="">
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>
   </div>
</template>

<script>
// 深拷贝插件
import _ from 'lodash'
export default {
    data() {
        return {
            activeIndex:'0',
            tabPosition: 'left',
            addForm:{
                goods_name:'',
                goods_price:0,
                goods_weight:0,
                goods_number:0,
                goods_cat:[],
                pics:[],
                goods_introduce:'',
                attrs:[],
            },
            addFormRules:{
                goods_name:[
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                ],
                goods_price:[
                    { required: true, message: '请输入商品价格', trigger: 'blur' },
                ],
                goods_weight:[
                    { required: true, message: '请输入商品重量', trigger: 'blur' },
                ],
                goods_number:[
                    { required: true, message: '请输入商品数量', trigger: 'blur' },
                ],
                goods_cat:[
                    { required: true, message: '请选择商品分类', trigger: 'blur' },
                ]
            },
            cateList:[],
            cateProps:{
                value:'cat_id',
                label:'cat_name',
                children:'children',
            },
            // 动态参数列表数组
            manyTableData:[],
            // 静态属性列表
            onlyTableData:[],
            uploadPath:'https://lianghj.top:8888/api/private/v1/upload',
            headerObj:{ //上传组件请求头参数
                Authorization : window.sessionStorage.getItem("token")
            },
            dialogVisible:false,
            showPicPath:'',
        }
    },
    created(){
        this.getCateList()
    },
    methods:{
        async getCateList(){
            const {data:res} = await this.$http.get('categories');
            if(res.meta.status != 200){
                return this.$message.error("获取商品分类数据失败！");
            }
           
            this.cateList = res.data;
             console.log(this.cateList)
        },
        // 级联选择器
        handleChange(){
            console.log(this.addForm.goods_cat)
            if(this.addForm.goods_cat.length !==3){
                this.addForm.goods_cat = []
            }
        },
        // 标签页切换
        beforeTableave(activename,oldActivename){
            // 如果在第一个分类没有选中3级，不让它切换
            if(oldActivename=='0' && 
            this.addForm.goods_cat.length !==3){
                this.$message.error("请先选择商品分类")
                return false;
            }
        },
        // 点击标签切换
        async tabClick(){
            if(this.activeIndex == '1'){
                 const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes`,
                 {
                     params:{ sel:'many' }
                 });
                if(res.meta.status != 200){
                    return this.$message.error("获取动态商品参数数据失败！");
                }
                res.data.forEach(item=>{
                    item.attr_vals = item.attr_vals.length!==0 ? item.attr_vals.split(",") : []
                })
                this.manyTableData = res.data;
                console.log(this.manyTableData)
            }else if(this.activeIndex == '2'){
                 const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes`,
                 {
                     params:{ sel:'only' }
                 });
                if(res.meta.status != 200){
                    return this.$message.error("获取静态商品参数数据失败！");
                }
                this.onlyTableData = res.data;
                console.log(this.onlyTableData)
            }

        },
        // 点击预览时回调
        handlePreview(file){
            const picPath = file.response.data.url
            this.showPicPath = picPath
            this.dialogVisible = true

        },
        // 删除图片回掉
        handleRemove(file){
            //获取图片信息
            const filePath = file.response.data.tmp_path
            //获取索引
            const i = this.addForm.pics.findIndex(x=>{
                return x.pic === filePath   
            })
            // splice方法删除
            this.addForm.pics.splice(i,1)
            console.log(this.addForm)
        },
        // 上传成功回调
        handleSuccess(response){
            // 获取到图片对象
            const picInfo = {
                pic : response.data.tmp_path
            }
            //添加到数组
            this.addForm.pics.push(picInfo)
            console.log(this.addForm)
        },
        add(){
            this.$refs.addFormRef.validate( async vaild=>{
                if(!vaild) return this.$message.error("请填写必要的表当项！")
                // 发送请求

                // 变量指向的是对象的内存地址，不能直接通过 const a = obj 进行复制
                //必须通过深拷贝创建另一个不相关的对象  插件：lodash    cloneDeep(obj)
                const form  = _.cloneDeep(this.addForm)
                form.goods_cat = form.goods_cat.join(",")
                console.log(form)
                // 处理动态参数
                this.manyTableData.forEach(item=>{
                    const newObj = {
                        attr_id:item.attr_id,
                        attr_value:item.attr_value.join(","),
                    }
                    this.addForm.attrs.push(newObj)
                })

                // 处理静态属性
                 this.onlyTableData.forEach(item=>{
                    const newObj = {
                        attr_id:item.attr_id,
                        attr_value:item.attr_value.join(","),
                    }
                    this.addForm.attrs.push(newObj)
                })

                form.attrs = this.addForm.attrs

                //发送添加请求
                 const {data:res} = await this.$http.post(`goods`,form);
                if(res.meta.status != 201){
                    return this.$message.error("添加商品失败！");
                }
                this.$message.success("添加商品成功！");

                //添加成功后跳转
                this.$router.push('/goods')
            })
        }
    },
    computed:{
        cateId(){
            if(this.addForm.goods_cat.length===3){
                return this.addForm.goods_cat[2]
            }
            return null
        }
    }
}
</script>
<style lang="less" scoped>
.el-checkbox{
    margin: 0 10px 0 0 ;
}
.btnAdd{
    margin-top: 15px;
}
</style>